#encoding: utf-8

import logging
import requests
import simplejson

class coinException(Exception):
    pass
class TxException(coinException):
    pass

class coinRPC(object):
    def __init__(self, host, port, username,password):
        assert isinstance(host, (str,unicode))
        assert isinstance(port, (int,long))
        assert isinstance(username, (str,unicode))
        assert isinstance(password, (str,unicode))
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.session = requests.Session()
        self.auth = requests.auth.HTTPBasicAuth(self.username, self.password)
        self.url = 'http://%s:%s'%(self.host, self.port)
    def make_packet(self,method, params):
        assert isinstance(method, (unicode,str))
        assert isinstance(params, list)
        obj1 = {}
        obj1['jsonrpc'] = '1.0'
        obj1['id'] = 'coin_python_client'
        obj1['method'] = method
        obj1['params'] = params
        return simplejson.dumps(obj1)
    def getbalance(self, user=None):
        method = 'getbalance'
        if user is not None:
            params = [user,]
        else:
            params = []
        rsp = self.session.post(self.url, data=self.make_packet(method, params), auth=self.auth)
        if rsp.status_code != 200:
            pass
        return rsp.json()['result']
    def sendfrom(self, user, amount, peeraddress):
        #验证peeraddress，amount
        method = 'sendfrom'
        params = [user, peeraddress, amount]
        rsp = self.session.post(self.url, data=self.make_packet(method, params), auth=self.auth)
        txobj = rsp.json()
        if txobj['result'] is None:
            if txobj.has_key('error') and txobj['error'].has_key('message'):
                exobj = TxException(txobj['error'] ['message'])
                raise exobj
            else:
                raise TxException('transaction unknown error!')
        return rsp.json()['result']
    def getnewaddress(self, user):
        method = 'getnewaddress'
        params = [user,]
        rsp = self.session.post(self.url, data=self.make_packet(method, params), auth=self.auth)
        return rsp.json()['result']
    def listtransactions(self, user, count=10, offset=0):
        method = 'listtransactions'
        params = [user,count, offset]
        rsp = self.session.post(self.url, data = self.make_packet(method, params),auth = self.auth)
        return rsp.json()['result']
    def dumpprivkey(self,addr):
        method = 'dumpprivkey'
        params = [addr,]
        rsp = self.session.post(self.url, data=self.make_packet(method, params), auth=self.auth)
        return rsp.json()['result']
    def getreceivedbyaddress(self, addr, minf=1):
        method = 'getreceivedbyaddress'
        params = [addr, minf]
        rsp = self.session.post(self.url, data=self.make_packet(method, params), auth=self.auth)
        return rsp.json()['result']
    def gettransaction(self,txid):
        method = 'gettransaction'
        params = [txid, ]
        rsp = self.session.post(self.url, data=self.make_packet(method, params), auth=self.auth)
        txobj = rsp.json()
        if txobj['result'] is None:
            if txobj.has_key('error') and txobj['error'].has_key('message'):
                exobj = coinException(txobj['error'] ['message'])
                raise exobj
            else:
                raise coinException('unknown error!')
        return rsp.json()['result']
    def alltransaction(self):
        method = 'listtransactions'
        params = []
        rsp = self.session.post(self.url, data = self.make_packet(method, params),auth = self.auth)
        return rsp.json()['result']
    def getblockhash(self, height):
        method = 'getblockhash'
        params = [height,]
        rsp = self.session.post(self.url, data = self.make_packet(method, params),auth = self.auth)
        return rsp.json()['result']
    def getblock(self,blk_hash):
        method = 'getblock'
        params = [blk_hash,]
        rsp = self.session.post(self.url, data = self.make_packet(method, params),auth = self.auth)
        return rsp.json()['result']
    def getrawtransaction(self, txid, verbose=0):
        method = 'getrawtransaction'
        params = [txid,verbose]
        rsp = self.session.post(self.url, data = self.make_packet(method, params),auth = self.auth)
        return rsp.json()['result']
    def getblockcount(self):
        method = 'getblockcount'
        params = []
        rsp = self.session.post(self.url, data = self.make_packet(method, params),auth = self.auth)
        return rsp.json()['result']

if __name__ == '__main__':
    host = '127.0.0.1'
    port = 36345
    username = 'dirkcoinrpc'
    password = '4gVsx3DSzXFpNmZLyXAg3WwVQdQCZLH9wnuw8DPUsDXH'
    session = coinRPC(host, port, username, password)
    print session.getrawtransaction('c189a1e52a812d6aa87b34757ee2180be46423fab08579f04562b074c956e63b',1)
